#include "task_queue.h"

TaskQueue::TaskQueue(int capacity)
    : capacity_(capacity), size_(0)
{
}

bool TaskQueue::empty()
{
    return size_ == 0;
}

bool TaskQueue::full()
{
    return size_ == capacity_;
}

int TaskQueue::addTask(Task *task)
{
    unique_lock<mutex> lock(mtx_);
    if (full())
        return -1;
    tasks_.push(task);
    size_++;

    cond_.notify_one();
    return 0;
}

Task *TaskQueue::getTask()
{
    Task *ret;
    {
        unique_lock<mutex> lock(mtx_);
        cond_.wait(lock, [this]()
                   { return !isRunning_ || !empty(); });
        if (!isRunning_)
            return nullptr;
        ret = tasks_.front();
        tasks_.pop();
        size_--;
    }

    return ret;
}

void TaskQueue::wakeup()
{
    isRunning_ = false;
    cond_.notify_all();
}